<template>
  <div>
    <el-button size="mini" @click="handleSave">保存</el-button>
    <!-- <el-button size="mini">另存为答题卡</el-button> -->
    <!-- <el-button size="mini">另存为模板</el-button> -->
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
import qs from 'query-string';
import _ from 'lodash';
import ajaxAPI from '@/network/ajax.api';

const CARD_TYPE = {
  card: 'card',
  cardTemplate: 'cardTemplate',
};
const EDIT_TYPE = {
  add: 'add',
  edit: 'edit',
};

const urlParams = qs.parse(window.location.search);

export default {
  data() {
    return {
      cardType: CARD_TYPE.cardTemplate, // 是答题卡还是答题卡模板
      editType: EDIT_TYPE.add, // 是编辑还是新增

      contentHtml: '',
    };
  },
  computed: {
    saveAPI() {
      return ajaxAPI[this.cardType][this.editType];
    },
    saveParams() {
      const { contentHtml } = this;
      const { id, name } = urlParams;
      const params = {
        [{
          [CARD_TYPE.card]: 'cardName',
          [CARD_TYPE.cardTemplate]: 'templateName',
        }[this.cardType]]: name,
        contentHtml,
        contentJson: JSON.stringify(this.$store.state),
      };
      if (this.editType === EDIT_TYPE.edit || this.cardType === CARD_TYPE.card) {
        params.id = id;
      }
      return params;
    },
  },
  created() {
    this.initType();
  },
  methods: {
    ...mapMutations([
      'updateState',
    ]),
    initType() {
      const { id, type } = urlParams;
      this.cardType = type || CARD_TYPE.cardTemplate;
      this.editType = id ? EDIT_TYPE.edit : EDIT_TYPE.add;
    },
    handleSave: _.debounce(function handleSave() {
      const iframe = document.createElement('iframe');
      iframe.setAttribute('src', `/card-view-2.html${window.location.search}`);
      iframe.onload = () => {
        this.contentHtml = iframe.contentDocument.documentElement.outerHTML
          .replace(/<link\s[^>]+?as="script">/g, '')
          .replace(/<script\s.+?<\/script>/g, '')
          .replace(/<noscript>.+?<\/noscript>/g, '')
          .replace(/(?=\/css\/)/g, 'http://jshj007.com');
        document.body.removeChild(iframe);
        this.save();
      };
      document.body.appendChild(iframe);
    }, 300),
    async save() {
      try {
        await this.saveAPI(this.saveParams);
        this.$message('保存成功！');
      } catch (err) {
        this.$message(err.message);
      }
    },
  },
};
</script>
